<?php

namespace app\admin\controller\coupons;

use app\common\controller\Backend;
use app\api\controller\coupons\Basic;
use app\common\library\Auth;
use think\Db;

/**
 * 优惠券
 *
 * @icon fa fa-circle-o
 */
class Coupons extends Backend
{
    //protected $noNeedLogin = ['add'];
    /**
     * Coupon模型对象
     * @var \app\admin\model\coupons\Coupon
     */
    protected $model = null;
    protected $searchFields = 'id,name,number';
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\coupons\Coupons;
        $t=$this->thirdModel = new \addons\third\model\Third;
        $u=$this->userModel = new \app\common\model\User;
        $this->view->assign("statusdataList", $this->model->getStatusdataList());
        $this->view->assign("platformList", $this->model->getPlatformList());
    }

    public function import()
    {
        parent::import();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
     /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['couponcategory'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

 /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
     /**
     * 查看
     */
    public function indexThird()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage2();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $t
                ->with(['user'])
                ->where($where)
                //->where('thirdM.unionid','neq','')
                //->field('thirdM.*,u.nickname')
                ->paginate($limit);
             foreach ($list as $row) {
                
                $row->getRelation('user')->visible(['nickname']);
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

/**
     * Selectpage的实现方法
     *
     * 当前方法只是一个比较通用的搜索匹配,请按需重载此方法来编写自己的搜索逻辑,$where按自己的需求写即可
     * 这里示例了所有的参数，所以比较复杂，实现上自己实现只需简单的几行即可
     *
     */
    protected function selectpage2()
    {
        //设置过滤方法
        $this->request->filter(['trim', 'strip_tags', 'htmlspecialchars']);

        //搜索关键词,客户端输入以空格分开,这里接收为数组
        $word = (array)$this->request->request("q_word/a");
        //当前页
        $page = $this->request->request("pageNumber");
        //分页大小
        $pagesize = $this->request->request("pageSize");
        //搜索条件
        $andor = $this->request->request("andOr", "and", "strtoupper");
        //排序方式
        $orderby = (array)$this->request->request("orderBy/a");
        //显示的字段
        $field = $this->request->request("showField");
        //主键
        $primarykey = $this->request->request("keyField");
        //主键值
        $primaryvalue = $this->request->request("keyValue");
        //搜索字段
        $searchfield = (array)$this->request->request("searchField/a");
        //自定义搜索条件
        $custom = (array)$this->request->request("custom/a");
        //是否返回树形结构
        $istree = $this->request->request("isTree", 0);
        $ishtml = $this->request->request("isHtml", 0);
        if ($istree) {
            $word = [];
            $pagesize = 999999;
        }
        $order = [];
        foreach ($orderby as $k => $v) {
            $order[$v[0]] = $v[1];
        }
        $field = $field ? $field : 'name';

        //如果有primaryvalue,说明当前是初始化传值
        if ($primaryvalue !== null) {
            $where = [$primarykey => ['in', $primaryvalue]];
            $pagesize = 999999;
        } else {
            $where = function ($query) use ($word, $andor, $field, $searchfield, $custom) {
                $logic = $andor == 'AND' ? '&' : '|';
                $searchfield = is_array($searchfield) ? implode($logic, $searchfield) : $searchfield;
                $searchfield = str_replace(',', $logic, $searchfield);
                $word = array_filter(array_unique($word));
                if (count($word) == 1) {
                    $query->where($searchfield, "like", "%" . reset($word) . "%");
                } else {
                    $query->where(function ($query) use ($word, $searchfield) {
                        foreach ($word as $index => $item) {
                            $query->whereOr(function ($query) use ($item, $searchfield) {
                                $query->where($searchfield, "like", "%{$item}%");
                            });
                        }
                    });
                }
                if ($custom && is_array($custom)) {
                    foreach ($custom as $k => $v) {
                        if (is_array($v) && 2 == count($v)) {
                            $query->where($k, trim($v[0]), $v[1]);
                        } else {
                            $query->where($k, '=', $v);
                        }
                    }
                }
            };
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->thirdModel->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = [];
        $total = $this->thirdModel->where($where)->count();
        if ($total > 0) {
            if (is_array($adminIds)) {
                $this->thirdModel->where($this->dataLimitField, 'in', $adminIds);
            }

            $fields = is_array($this->selectpageFields) ? $this->selectpageFields : ($this->selectpageFields && $this->selectpageFields != '*' ? explode(',', $this->selectpageFields) : []);

            //如果有primaryvalue,说明当前是初始化传值,按照选择顺序排序
            if ($primaryvalue !== null && preg_match("/^[a-z0-9_\-]+$/i", $primarykey)) {
                $primaryvalue = array_unique(is_array($primaryvalue) ? $primaryvalue : explode(',', $primaryvalue));
                //修复自定义data-primary-key为字符串内容时，给排序字段添加上引号
                $primaryvalue = array_map(function ($value) {
                    return '\'' . $value . '\'';
                }, $primaryvalue);

                $primaryvalue = implode(',', $primaryvalue);

                $this->thirdModel->orderRaw("FIELD(`{$primarykey}`, {$primaryvalue})");
            } else {
                $this->thirdModel->order($order);
            }

            $datalist = $this->thirdModel->where($where)
                ->page($page, $pagesize)
                ->select();

            foreach ($datalist as $index => $item) {
                unset($item['password'], $item['salt']);
                if ($this->selectpageFields == '*') {
                    $result = [
                        $primarykey => isset($item[$primarykey]) ? $item[$primarykey] : '',
                        $field      => isset($item[$field]) ? $item[$field] : '',
                    ];
                } else {
                    $result = array_intersect_key(($item instanceof Model ? $item->toArray() : (array)$item), array_flip($fields));
                }
                $result['pid'] = isset($item['pid']) ? $item['pid'] : (isset($item['parent_id']) ? $item['parent_id'] : 0);
                $list[] = $result;
            }
            if ($istree && !$primaryvalue) {
                $tree = Tree::instance();
                $tree->init(collection($list)->toArray(), 'pid');
                $list = $tree->getTreeList($tree->getTreeArray(0), $field);
                if (!$ishtml) {
                    foreach ($list as &$item) {
                        $item = str_replace('&nbsp;', ' ', $item);
                    }
                    unset($item);
                }
            }
        }
        //这里一定要返回有list这个字段,total是可选的,如果total<=list的数量,则会隐藏分页按钮
        return json(['list' => $list, 'total' => $total]);
    }
    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                if($params['platform']==1){
                  //员工系统，不存储unionid
                  $params['unionid']='';   
                }
                if($params['platform']==2){
                    //积分商城系统，不存储员工信息
                    $params['name']='';
                    $params['staffnumber']='';
                    //验证表是否存在
                    //这是要查询的表的原始名称（全名）
                    $tableName = config('database.prefix').'third';
                    
                    $isTable = db()->query('SHOW TABLES LIKE '."'".$tableName."'");
                    if($isTable){
                        //表存在
                        if(isset($params['unionid'])){
                        $params['unionid']=Db::name('third')->where('id',$params['unionid'])->value('unionid'); 
                        if(empty($params['unionid'])){
                             $this->error('用户登录授权未完成，未获取到该用户的unionid');
                        }
                        }
                    }else{
                        //表不存在
                        $this->error('未检测到第三方用户登陆表，请安装第三方登录插件');
                    }
                }
                $result = true;
                $resultData=$this->createAutoCoupon($params);
                if ($result !== false && isset($resultData['status']) && $resultData['status']==1) {
                    $this->success('创建成功');
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
     /**
     * 三方接口,自动生成优惠券模块
     *
     * @param string $platform 平台，1代表员工系统，,2代表 积分商城
     * @param string $type     优惠券类型，对应后台优惠券类型id
     * @param string $num      生成同类型优惠券数量,默认是1
     * @param string $unionid  积分商城传此参数，唯一识别用户 
     * @param string $name     用户姓名，HR系统传此参数
     * @param string $staffNumber     员工工号，HR系统传此参数// $platform=1,$type,$num=1,$unionid=null,$name=null,$staffNumber=null
     */
    public function createAutoCoupon($datas,$num=1)
    {
          //var_dump($datas);exit;
          $j=1;
          //查询该类型优惠券的有效期
          $coupon_category_effective=Db::name('coupons_category')->where('id',$datas['coupon_category_id'])->value('effective');
          $coupon_category_effective=intval($coupon_category_effective);
          if(!$coupon_category_effective){
            $this->error('暂无该类型优惠券');
          }
          $datas['begintime']=strtotime($datas['begintime']);
          //设定开始时间未当天领取通过时间
          $datas['endtime']=strtotime(date("Y-m-d H:i", $datas['begintime']+$coupon_category_effective*24*60*60));
         //HR系统过来的数据
          $datas['createtime']=time();
          $datas['updatetime']=time();
         if($datas['platform']==1){
             $datas['unionid']='';
         }
         //积分商城过来的优惠券
         if($datas['platform']==2){
           $datas['staffnumber']='';
           $datas['name']='';
           }
          //var_dump($num);exit;
          //执行循环插入
          $callbackInfo=[];
          for($i=1;$i<=intval($num);$i++){
            //生成唯一的12位优惠券编码
            $tempsn = unpack('H12',str_shuffle(sha1(uniqid())));
            $datas['number'] = $tempsn[1];
            
            $basic=new Basic;
            $datas['qrcodeimage']=$basic->getQrCode(1,$datas['number'],$datas['coupon_category_id']);
               Db::startTrans();
               $Coupon = new \app\admin\model\coupons\Coupons();
                  try { 
                          $resc=$Coupon->allowField(true)->save($datas);
                            Db::commit();
                            $callbackInfo[$i-1]['coupon_num']=$datas['number'];
                            $callbackInfo[$i-1]['coupon_category_id']=$datas['coupon_category_id'];
                            $callbackInfo[$i-1]['begintime']=$datas['begintime'];
                            $callbackInfo[$i-1]['endtime']=$datas['endtime'];
                            $j++;
                        } catch (ValidateException $e) {
                            Db::rollback();
                            $j--;
                            //$this->error($e->getMessage());
                        } catch (PDOException $e) {
                            Db::rollback();
                            $j--;
                            //$this->error($e->getMessage());
                        } catch (Exception $e) {
                            Db::rollback();
                            $j--;
                            //$this->error($e->getMessage());
                        }
                       
             }
           if ($i==$j) {
               $n=$i-1;
               $res=['status'=>1,'message'=>'优惠券创建成功，共生成'.$n.'条优惠券信息','callbackInfo'=>$callbackInfo];
            } else {
                $res=['status'=>0,'message'=>'优惠券未全部创建成功，需生成'.$i.'条优惠券，成功生成'.$j.'条优惠券信息','callbackInfo'=>$callbackInfo];
             }
            
          return $res;
          //$this->success('返回成功',$res);

    }

}